<template>
  <div class="data-history">
    <!-- 头部区域 -->
    <div class="header-section">
      <h2>健康数据历史记录</h2>
      <p class="subheader">全方位追踪您的健康指标变化趋势</p>

      <!-- 筛选与视图切换区 -->
      <div class="filter-view-container">
        <div class="date-filter">
          <label>日期范围：</label>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateFilter"
            value-format="YYYY-MM-DD"
            class="date-picker"
          />
        </div>

        <div class="view-switch">
          <label>视图模式：</label>
          <el-radio-group v-model="currentView" @change="handleViewChange" class="radio-group">
            <el-radio label="list" class="radio-btn">
              <el-icon><list /></el-icon> 列表视图
            </el-radio>
            <el-radio label="chart" class="radio-btn">
              <el-icon><pie-chart /></el-icon> 图表视图
            </el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>

    <!-- 加载状态（美化） -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载健康数据...</p>
    </div>

    <!-- 统计概览（卡片悬浮效果增强） -->
    <div v-if="!loading" class="stats-overview">
      <div class="stat-card hover-lift">
        <div class="stat-icon">
          <el-icon><document /></el-icon>
        </div>
        <div class="stat-value">{{ totalRecords }}</div>
        <div class="stat-label">总记录数</div>
      </div>
      <div class="stat-card hover-lift warning">
        <div class="stat-icon">
          <el-icon><warning /></el-icon>
        </div>
        <div class="stat-value">{{ abnormalRecords }}</div>
        <div class="stat-label">异常记录</div>
      </div>
      <div class="stat-card hover-lift success">
        <div class="stat-icon">
          <el-icon><check /></el-icon>
        </div>
        <div class="stat-value">{{ normalRecords }}</div>
        <div class="stat-label">正常记录</div>
      </div>
      <div class="stat-card hover-lift info">
        <div class="stat-icon">
          <el-icon><data-line /></el-icon>
        </div>
        <div class="stat-value">{{ averageBMI }}</div>
        <div class="stat-label">平均BMI</div>
      </div>
    </div>

    <!-- 列表视图（优化表格样式） -->
    <div v-if="!loading && currentView === 'list'" class="list-view">
      <div class="table-container card-shadow">
        <div class="table-header">
          <h3>健康指标记录列表</h3>
          <p class="table-desc">共 {{ totalRecords }} 条记录，显示最新数据</p>
        </div>
        <div class="table-wrapper">
          <el-table 
            :data="tableData" 
            border 
            stripe 
            :row-class-name="tableRowClassName"
            class="custom-table"
          >
            <el-table-column label="日期时间" prop="submitTime" width="200">
              <template #default="scope">{{ formatDate(scope.row.submitTime) }}</template>
            </el-table-column>
            <el-table-column label="指标类型" width="120">
              <template #default="scope">{{ getIndicatorTypeText(scope.row) }}</template>
            </el-table-column>
            <el-table-column label="收缩压(apHi)" prop="apHi" width="120" />
            <el-table-column label="舒张压(apLo)" prop="apLo" width="120" />
            <el-table-column label="胆固醇" prop="cholesterol" width="120">
              <template #default="scope">{{ getCholesterolText(scope.row.cholesterol) }}</template>
            </el-table-column>
            <el-table-column label="BMI" prop="bmi" width="100" />
            <el-table-column label="血糖" prop="gluc" width="100">
              <template #default="scope">{{ getGlucText(scope.row.gluc) }}</template>
            </el-table-column>
            <el-table-column label="状态" width="120">
              <template #default="scope">
                <el-tag :type="scope.row.isAbnormal === 1 ? 'danger' : 'success'" class="status-tag">
                  <span :class="['status-dot', scope.row.isAbnormal === 1 ? 'abnormal' : 'normal']"></span>
                  {{ scope.row.isAbnormal === 1 ? '异常' : '正常' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="viewDetails(scope.row)"
                  class="view-btn"
                >
                  <el-icon><view /></el-icon> 详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页控件（美化） -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalRecords"
            class="pagination"
          />
        </div>

        <div v-if="tableData.length === 0" class="no-data">
          <el-empty description="暂无健康数据记录" />
        </div>
      </div>
    </div>

    <!-- 图表视图（修复ECharts组件+美化） -->
    <div v-if="!loading && currentView === 'chart'" class="chart-view">
      <!-- 血压趋势图 -->
      <div class="chart-card card-shadow hover-lift">
        <div class="chart-header">
          <h3>血压变化趋势</h3>
          <p class="chart-desc">收缩压(apHi)与舒张压(apLo)的波动情况</p>
        </div>
        <div class="chart-wrapper">
          <e-charts 
            :option="bloodPressureOption" 
            style="width: 100%; height: 300px" 
            autoresize
          />
        </div>
      </div>

      <!-- 血糖+胆固醇趋势图 -->
      <div class="chart-card card-shadow hover-lift">
        <div class="chart-header">
          <h3>血糖&胆固醇变化趋势</h3>
          <p class="chart-desc">血糖与胆固醇指标的变化对比</p>
        </div>
        <div class="chart-wrapper">
          <e-charts 
            :option="glucCholOption" 
            style="width: 100%; height: 300px" 
            autoresize
          />
        </div>
      </div>

      <!-- 体重+BMI趋势图 -->
      <div class="chart-card card-shadow hover-lift">
        <div class="chart-header">
          <h3>体重&BMI变化趋势</h3>
          <p class="chart-desc">体重与BMI指数的关联变化</p>
        </div>
        <div class="chart-wrapper">
          <e-charts 
            :option="weightBmiOption" 
            style="width: 100%; height: 300px" 
            autoresize
          />
        </div>
      </div>
    </div>

    <!-- 详情弹窗（美化） -->
    <el-dialog
      title="健康数据详情"
      :visible.sync="showDetails"
      width="600px"
      @close="closeDetails"
      class="detail-dialog"
      :before-close="handleDialogClose"
    >
      <div class="detail-info" v-if="selectedRecord">
        <div class="detail-row">
          <div class="label">数据ID：</div>
          <div class="value">{{ selectedRecord.indicatorId }}</div>
        </div>
        <div class="detail-row">
          <div class="label">提交时间：</div>
          <div class="value">{{ formatDate(selectedRecord.submitTime) }}</div>
        </div>
        <div class="detail-row">
          <div class="label">年龄：</div>
          <div class="value">{{ selectedRecord.age }}岁 ({{ selectedRecord.ageGroup }})</div>
        </div>
        <div class="detail-row">
          <div class="label">性别：</div>
          <div class="value">{{ selectedRecord.gender === 1 ? '男' : '女' }}</div>
        </div>
        <div class="detail-row">
          <div class="label">身高/体重：</div>
          <div class="value">{{ selectedRecord.height }}cm / {{ selectedRecord.weight }}kg</div>
        </div>
        <div class="detail-row">
          <div class="label">血压：</div>
          <div class="value">{{ selectedRecord.apHi }} / {{ selectedRecord.apLo }} mmHg</div>
        </div>
        <div class="detail-row">
          <div class="label">胆固醇：</div>
          <div class="value">{{ getCholesterolText(selectedRecord.cholesterol) }}</div>
        </div>
        <div class="detail-row">
          <div class="label">血糖：</div>
          <div class="value">{{ getGlucText(selectedRecord.gluc) }}</div>
        </div>
        <div class="detail-row">
          <div class="label">BMI：</div>
          <div class="value">{{ selectedRecord.bmi }} ({{ selectedRecord.bmiCat }})</div>
        </div>
        <div class="detail-row">
          <div class="label">健康状态：</div>
          <div class="value" :class="selectedRecord.isAbnormal === 1 ? 'risk-high' : 'risk-normal'">
            {{ selectedRecord.isAbnormal === 1 ? '异常' : '正常' }}
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="closeDetails" class="close-btn">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import api from '@/utils/axiosConfig'
// 引入Element Plus组件和图标
import { 
  ElDatePicker, ElRadioGroup, ElRadio, ElTable, ElTableColumn, 
  ElPagination, ElButton, ElTag, ElDialog, ElMessage, ElEmpty 
} from 'element-plus'
import { 
  List, PieChart, Document, Warning, Check, 
  DataLine, View, Close 
} from '@element-plus/icons-vue'
// 引入正确的ECharts组件
import ECharts from 'vue-echarts'
import * as echarts from 'echarts'
// 引入userStore
import { useUserStore } from '@/stores/user'

export default {
  name: 'DataHistory',
  components: {
    ElDatePicker, ElRadioGroup, ElRadio, ElTable, ElTableColumn,
    ElPagination, ElButton, ElTag, ElDialog, ElMessage, ElEmpty,
      ECharts, // 注册vue-echarts组件
      List, PieChart, Document, Warning, Check, DataLine, View, Close
  },
  setup() {
    // 状态管理
    const loading = ref(false)
    const showDetails = ref(false)
    const selectedRecord = ref(null)
    const allRecords = ref([])
    const currentView = ref('list')
    const dateRange = ref([])
    const pageNum = ref(1)
    const pageSize = ref(10)

    // 初始化默认近7天日期
    const initDefaultDateRange = () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 7 * 24 * 60 * 60 * 1000)
      dateRange.value = [
        start.toISOString().split('T')[0],
        end.toISOString().split('T')[0]
      ]
    }

    // 加载数据
    const loadData = async () => {
      try {
        loading.value = true
        // 使用与其他组件一致的方式获取用户ID
        let userId = null
        const userStore = useUserStore()
        
        // 添加详细调试日志
        console.log('localStorage中的所有键:', Object.keys(localStorage))
        
        // 方式1: 尝试从userStore获取
        if (userStore.userInfo) {
          const possibleIdFields = ['userId', 'id', 'user_id']
          for (const field of possibleIdFields) {
            if (userStore.userInfo[field] && !isNaN(parseInt(userStore.userInfo[field]))) {
              userId = parseInt(userStore.userInfo[field])
              console.log('从userStore.userInfo.', field, '获取到用户ID:', userId)
              break
            }
          }
          
          // 尝试嵌套路径
          if (!userId && userStore.userInfo.data && userStore.userInfo.data.id) {
            userId = parseInt(userStore.userInfo.data.id)
            console.log('从userStore.userInfo.data.id获取到用户ID:', userId)
          }
          
          if (!userId && userStore.userInfo.data && userStore.userInfo.data.userId) {
            userId = parseInt(userStore.userInfo.data.userId)
            console.log('从userStore.userInfo.data.userId获取到用户ID:', userId)
          }
        }
        
        // 方式2: 从localStorage直接获取userInfo
        if (!userId) {
          const userInfoStr = localStorage.getItem('userInfo')
          console.log('userInfo字符串:', userInfoStr)
          
          if (userInfoStr) {
            try {
              const userInfo = JSON.parse(userInfoStr)
              console.log('解析后的userInfo对象:', userInfo)
              
              const possibleIdFields = ['userId', 'id', 'user_id']
              for (const field of possibleIdFields) {
                if (userInfo[field] && !isNaN(parseInt(userInfo[field]))) {
                  userId = parseInt(userInfo[field])
                  console.log('从localStorage userInfo.', field, '获取到用户ID:', userId)
                  break
                }
              }
              
              // 尝试嵌套路径
              if (!userId && userInfo.data && userInfo.data.id) {
                userId = parseInt(userInfo.data.id)
                console.log('从localStorage data.id获取到用户ID:', userId)
              }
              
              if (!userId && userInfo.data && userInfo.data.userId) {
                userId = parseInt(userInfo.data.userId)
                console.log('从localStorage data.userId获取到用户ID:', userId)
              }
              
              if (!userId && userInfo.userInfo && userInfo.userInfo.userId) {
                userId = parseInt(userInfo.userInfo.userId)
                console.log('从localStorage userInfo.userInfo.userId获取到用户ID:', userId)
              }
            } catch (parseError) {
              console.error('解析userInfo时出错:', parseError)
            }
          }
        }
        
        // 方式3: 直接尝试获取userId键
        if (!userId) {
          const directUserId = localStorage.getItem('userId')
          if (directUserId && !isNaN(parseInt(directUserId))) {
            userId = parseInt(directUserId)
            console.log('从localStorage直接键userId获取到用户ID:', userId)
          }
        }
        
        // 方式4: 尝试获取id键
        if (!userId) {
          const directId = localStorage.getItem('id')
          if (directId && !isNaN(parseInt(directId))) {
            userId = parseInt(directId)
            console.log('从localStorage直接键id获取到用户ID:', userId)
          }
        }
        
        // 如果仍然没有获取到用户ID，显示错误并提示登录
        if (!userId || isNaN(userId)) {
          console.error('未找到有效的用户ID')
          ElMessage.error('用户信息无效，请先登录')
          allRecords.value = []
          return
        }
        
        const response = await api.get('/health-indicator/getByUserId', {
          params: { userId }
        })
        allRecords.value = response.data || []
        handleDateFilter()
      } catch (error) {
        console.error('获取健康数据失败:', error)
        ElMessage.error('获取数据失败，请稍后重试')
        allRecords.value = []
      } finally {
        loading.value = false
      }
    }

    // 日期筛选
    const handleDateFilter = () => {
      if (!dateRange.value.length) return
      const [startDate, endDate] = dateRange.value
      const startTimestamp = new Date(startDate).getTime()
      const endTimestamp = new Date(endDate + ' 23:59:59').getTime()

      const filtered = allRecords.value.filter(record => {
        const recordTimestamp = new Date(record.submitTime).getTime()
        return recordTimestamp >= startTimestamp && recordTimestamp <= endTimestamp
      }).sort((a, b) => new Date(b.submitTime) - new Date(a.submitTime))

      allRecords.value = filtered
      pageNum.value = 1
    }

    // 分页处理
    const tableData = computed(() => {
      const startIndex = (pageNum.value - 1) * pageSize.value
      const endIndex = startIndex + pageSize.value
      return allRecords.value.slice(startIndex, endIndex)
    })

    // 表格行样式（异常记录高亮）
    const tableRowClassName = ({ row }) => {
      return row.isAbnormal === 1 ? 'abnormal-row' : ''
    }

    // 分页事件
    const handleSizeChange = (val) => {
      pageSize.value = val
      pageNum.value = 1
    }
    const handleCurrentChange = (val) => {
      pageNum.value = val
    }

    // 视图切换
    const handleViewChange = () => {
      if (currentView.value === 'chart') {
        initCharts()
      }
    }

    // 图表初始化
    const bloodPressureOption = ref({})
    const glucCholOption = ref({})
    const weightBmiOption = ref({})

    const initCharts = () => {
      const sortedRecords = [...allRecords.value].sort((a, b) => new Date(a.submitTime) - new Date(b.submitTime))
      const xAxisData = sortedRecords.map(item => formatDate(item.submitTime, 'short'))

      // 血压图表（添加网格线和动画）
      bloodPressureOption.value = {
        tooltip: { trigger: 'axis', backgroundColor: 'rgba(255,255,255,0.9)', borderColor: '#eee' },
        legend: { data: ['收缩压(apHi)', '舒张压(apLo)'], top: 0 },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'category', data: xAxisData, axisLine: { lineStyle: { color: '#ddd' } } },
        yAxis: { 
          type: 'value', 
          name: '血压(mmHg)',
          axisLine: { lineStyle: { color: '#ddd' } },
          splitLine: { lineStyle: { color: '#f5f5f5' } }
        },
        series: [
          {
            name: '收缩压(apHi)',
            type: 'line',
            data: sortedRecords.map(item => item.apHi),
            itemStyle: { color: '#ef4444' },
            lineStyle: { color: '#ef4444' },
            smooth: true,
            animationDuration: 1000
          },
          {
            name: '舒张压(apLo)',
            type: 'line',
            data: sortedRecords.map(item => item.apLo),
            itemStyle: { color: '#3b82f6' },
            lineStyle: { color: '#3b82f6' },
            smooth: true,
            animationDuration: 1000
          }
        ]
      }

      // 血糖+胆固醇图表
      glucCholOption.value = {
        tooltip: { trigger: 'axis', backgroundColor: 'rgba(255,255,255,0.9)', borderColor: '#eee' },
        legend: { data: ['血糖', '胆固醇'], top: 0 },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'category', data: xAxisData, axisLine: { lineStyle: { color: '#ddd' } } },
        yAxis: { 
          type: 'value',
          axisLine: { lineStyle: { color: '#ddd' } },
          splitLine: { lineStyle: { color: '#f5f5f5' } }
        },
        series: [
          {
            name: '血糖',
            type: 'line',
            data: sortedRecords.map(item => item.gluc),
            itemStyle: { color: '#10b981' },
            lineStyle: { color: '#10b981' },
            smooth: true,
            animationDuration: 1000
          },
          {
            name: '胆固醇',
            type: 'line',
            data: sortedRecords.map(item => item.cholesterol),
            itemStyle: { color: '#f59e0b' },
            lineStyle: { color: '#f59e0b' },
            smooth: true,
            animationDuration: 1000
          }
        ]
      }

      // 体重+BMI图表
      weightBmiOption.value = {
        tooltip: { trigger: 'axis', backgroundColor: 'rgba(255,255,255,0.9)', borderColor: '#eee' },
        legend: { data: ['体重(kg)', 'BMI'], top: 0 },
        grid: { left: '3%', right: '10%', bottom: '3%', containLabel: true },
        xAxis: { type: 'category', data: xAxisData, axisLine: { lineStyle: { color: '#ddd' } } },
        yAxis: [
          { 
            type: 'value', 
            name: '体重(kg)', 
            min: Math.min(...sortedRecords.map(item => item.weight)) - 2,
            axisLine: { lineStyle: { color: '#ddd' } },
            splitLine: { lineStyle: { color: '#f5f5f5' } }
          },
          { 
            type: 'value', 
            name: 'BMI', 
            min: 18, 
            max: 28, 
            position: 'right',
            axisLine: { lineStyle: { color: '#ddd' } },
            splitLine: { show: false }
          }
        ],
        series: [
          {
            name: '体重(kg)',
            type: 'line',
            yAxisIndex: 0,
            data: sortedRecords.map(item => item.weight),
            itemStyle: { color: '#8b5cf6' },
            lineStyle: { color: '#8b5cf6' },
            smooth: true,
            animationDuration: 1000
          },
          {
            name: 'BMI',
            type: 'line',
            yAxisIndex: 1,
            data: sortedRecords.map(item => item.bmi),
            itemStyle: { color: '#ec4899' },
            lineStyle: { color: '#ec4899' },
            smooth: true,
            animationDuration: 1000
          }
        ]
      }
    }

    // 工具函数
    const formatDate = (dateString, type = 'full') => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      if (type === 'short') {
        return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
      }
      return date.toLocaleString('zh-CN', {
        year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit', minute: '2-digit', second: '2-digit'
      })
    }

    const getIndicatorTypeText = (record) => {
      if (record.apHi !== undefined && record.apLo !== undefined) return '血压'
      if (record.cholesterol !== undefined) return '胆固醇'
      if (record.bmi !== undefined) return 'BMI'
      if (record.gluc !== undefined) return '血糖'
      return '综合指标'
    }

    const getCholesterolText = (value) => {
      switch (value) {
        case 1: return '正常'
        case 2: return '高于正常'
        case 3: return '远高于正常'
        default: return value
      }
    }

    const getGlucText = (value) => {
      switch (value) {
        case 1: return '正常'
        case 2: return '高于正常'
        case 3: return '远高于正常'
        default: return value
      }
    }

    // 详情弹窗
    const viewDetails = (record) => {
      selectedRecord.value = { ...record }
      showDetails.value = true
    }

    const closeDetails = () => {
      showDetails.value = false
      selectedRecord.value = null
    }

    const handleDialogClose = (done) => {
      closeDetails()
      done()
    }

    // 统计计算
    const totalRecords = computed(() => allRecords.value.length)
    const abnormalRecords = computed(() => allRecords.value.filter(r => r.isAbnormal === 1).length)
    const normalRecords = computed(() => allRecords.value.filter(r => r.isAbnormal === 0).length)
    const averageBMI = computed(() => {
      if (allRecords.value.length === 0) return '0.0'
      const sum = allRecords.value.reduce((acc, r) => acc + (r.bmi || 0), 0)
      return (sum / allRecords.value.length).toFixed(1)
    })

    // 初始化
    onMounted(async () => {
      initDefaultDateRange()
      await loadData()
    })

    return {
      loading, showDetails, selectedRecord, currentView, dateRange,
      pageNum, pageSize, tableData, totalRecords, abnormalRecords,
      normalRecords, averageBMI, bloodPressureOption, glucCholOption,
      weightBmiOption, formatDate, getIndicatorTypeText, getCholesterolText,
      getGlucText, viewDetails, closeDetails, handleDateFilter, handleViewChange,
      handleSizeChange, handleCurrentChange, tableRowClassName, handleDialogClose
    }
  }
}
</script>

<style scoped>
/* 基础容器样式 */
.data-history {
  background: linear-gradient(135deg, #f9fafb 0%, #f1f5f9 100%);
  border-radius: 16px;
  padding: 30px;
  margin: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

/* 头部样式 */
.header-section {
  margin-bottom: 30px;
  text-align: center;
}

.header-section h2 {
  background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 8px;
}

.subheader {
  color: #64748b;
  font-size: 16px;
  margin: 0;
}

/* 筛选与视图切换区 */
.filter-view-container {
  display: flex;
  gap: 20px;
  margin: 20px 0;
  align-items: center;
  flex-wrap: wrap;
  justify-content: center;
  padding: 15px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.date-filter, .view-switch {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-filter label, .view-switch label {
  font-weight: 600;
  color: #334155;
  white-space: nowrap;
}

.date-picker {
  width: 320px;
}

.radio-group {
  background: #f8fafc;
  padding: 5px;
  border-radius: 6px;
}

.radio-btn {
  padding: 6px 16px;
  border-radius: 4px;
  transition: all 0.2s;
}

.radio-btn:hover {
  background: rgba(59, 130, 246, 0.05);
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #64748b;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #e2e8f0;
  border-top: 3px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 统计卡片 */
.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 12px;
  text-align: center;
  transition: all 0.3s ease;
  border-left: 4px solid #94a3b8;
}

.stat-card.success {
  border-left-color: #10b981;
}

.stat-card.warning {
  border-left-color: #f59e0b;
}

.stat-card.info {
  border-left-color: #3b82f6;
}

.stat-icon {
  font-size: 24px;
  margin-bottom: 12px;
  color: #64748b;
}

.stat-card.success .stat-icon {
  color: #10b981;
}

.stat-card.warning .stat-icon {
  color: #f59e0b;
}

.stat-card.info .stat-icon {
  color: #3b82f6;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 8px;
}

.stat-label {
  color: #64748b;
  font-size: 14px;
}

/* 列表视图 */
.list-view {
  margin-top: 20px;
}

.table-container {
  background: white;
  border-radius: 12px;
  overflow: hidden;
}

.table-header {
  padding: 20px;
  border-bottom: 1px solid #f1f5f9;
}

.table-header h3 {
  margin: 0;
  color: #1e293b;
  font-size: 18px;
  font-weight: 600;
}

.table-desc {
  color: #64748b;
  margin: 5px 0 0 0;
  font-size: 14px;
}

.custom-table {
  width: 100%;
}

.custom-table th {
  background: #f8fafc;
  font-weight: 600;
  color: #334155;
}

.abnormal-row {
  background-color: #fef2f2 !important;
}

.status-tag {
  display: flex;
  align-items: center;
  gap: 6px;
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
}

.status-dot.normal {
  background-color: #10b981;
}

.status-dot.abnormal {
  background-color: #ef4444;
}

.view-btn {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  padding: 15px 20px;
  background: #f8fafc;
  text-align: right;
}

.pagination {
  --el-pagination-item-active-bg-color: #3b82f6;
}

/* 无数据样式 */
.no-data {
  padding: 60px 20px;
  text-align: center;
}

/* 图表视图 */
.chart-view {
  display: grid;
  grid-template-columns: 1fr;
  gap: 30px;
  margin-top: 20px;
}

.chart-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.chart-header {
  padding: 20px;
  border-bottom: 1px solid #f1f5f9;
}

.chart-header h3 {
  margin: 0;
  color: #1e293b;
  font-size: 18px;
  font-weight: 600;
}

.chart-desc {
  color: #64748b;
  margin: 5px 0 0 0;
  font-size: 14px;
}

.chart-wrapper {
  padding: 20px;
}

/* 详情弹窗 */
.detail-dialog {
  --el-dialog-content-padding: 0;
}

.detail-info {
  padding: 25px;
}

.detail-row {
  display: flex;
  margin-bottom: 16px;
  line-height: 24px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-row .label {
  font-weight: 600;
  color: #64748b;
  width: 110px;
  flex-shrink: 0;
}

.detail-row .value {
  color: #1e293b;
  flex: 1;
}

.risk-high {
  color: #ef4444;
  font-weight: 500;
}

.risk-normal {
  color: #10b981;
  font-weight: 500;
}

.close-btn {
  background: #3b82f6;
  color: white;
  &:hover {
    background: #2563eb;
  }
}

/* 通用动画效果 */
.hover-lift {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.hover-lift:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08);
}

.card-shadow {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .data-history {
    padding: 20px 15px;
    margin: 10px;
  }

  .filter-view-container {
    flex-direction: column;
    align-items: flex-start;
    padding: 15px 10px;
  }

  .date-picker {
    width: 100%;
  }

  .stats-overview {
    grid-template-columns: 1fr;
  }

  .detail-row {
    flex-direction: column;
  }

  .detail-row .label {
    margin-bottom: 4px;
    width: 100%;
  }
}
</style>